<?php
namespace Todo\Service;
use Todo\Model\Sys\EmailModel;

/**
 * Created by PhpStorm.
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:08
 */
class EmailService extends BaseService
{
    private static $__INSTANCE = null;
    protected $_model = null;

    public function __construct()
    {
        $this->_model = new EmailModel();
    }

    public static function getInstance(){
        if(!self::$__INSTANCE) self::$__INSTANCE = new EmailService();

        return self::$__INSTANCE;
    }

    /**
     * 产生一封新邮件
     * @param array $data 邮件参数
     * @return int
     */
    public function add($data){
        if(is_array($data['params'])) $data['params'] = json_encode($data['params']);
        return $this->_model->insert($data);
    }

    /**
     * 发送邮件的功能封闭
     * @param array $data email,nickname,content,url
     */
    public function send($data){
        include APP_PATH.'../framework/Vendor/PHPMailer/PHPMailerAutoload.php';

        $mail = new \PHPMailer(); //实例化
        $mail->SMTPDebug = 1;
        $mail->Debugoutput = 'echo';
        $mail->IsSMTP(); // 启用SMTP
        $mail->Host=C('MAIL.HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->SMTPAuth = C('MAIL.SMTPAUTH'); //启用smtp认证
        $mail->Username = C('MAIL.USERNAME'); //你的邮箱名
        $mail->Password = C('MAIL.PASSWORD') ; //邮箱密码
        $mail->From = C('MAIL.FROM'); //发件人地址（也就是你的邮箱地址）
        $mail->FromName = C('MAIL.FROMNAME'); //发件人姓名
        $mail->AddAddress($data['email'], $data['nickname']);
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(1); // 是否HTML格式邮件
        $mail->CharSet=C('MAIL.CHARSET'); //设置邮件编码
        $mail->Subject = $data['title']; //邮件主题
        $mail->Body = $data['content']; //邮件内容
        $mail->AltBody = "请在浏览器中打开以下链接:".$data['url']; //邮件正文不支持HTML的备用显示
        $mail->Send();
    }

    public function sendmail(){
        $subject = "=?GBK?B?".base64_encode('邮件主题')."?=";    //解决邮件主题乱码问题，GBK编码格式
        $header = "From: 发件人姓名 <username@domain.com>\n";
        $header .= "Return-Path: <username@domain.com>\n";	 //防止被当做垃圾邮件，但在sina邮箱里不起作用
        $header .= "MIME-Version: 1.0\n";
        $header .= "Content-type: text/html; charset=utf-8\n";    //邮件内容为utf-8编码
        $header .= "Content-Transfer-Encoding: 8bit\r\n";	 //注意header的结尾，只有这个后面有\r
        ini_set('sendmail_from', 'username@domain.com');	 //解决mail的一个bug
        $send_message = wordwrap($send_message, 70);	 //每行最多70个字符,这个是mail方法的限制
        mail($email, $subject, $send_message, $header);
    }
}